package com.example.testdemo.bubble;

import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.example.testdemo.R;
import com.example.testdemo.trigonView.TriangleView;

/**
 * Created by MrYan on 2018/8/30.
 * 仿微信气泡弹窗
 */

public class BubbleWindow implements ViewTreeObserver.OnGlobalLayoutListener {
    private static final String TAG = "BubbleWindow";
    private PopupWindow mPopupWindow;
    private Context context;
    private int[] location;
    private TriangleView triangleView;
    private View view;
    private View attachView;
    private int measuredHeight;
    private int measuredWidth;

    public BubbleWindow(Context context) {
        this.context = context;
        initPopupWindowView();
    }

    private void initPopupWindowView() {
        view = LayoutInflater.from(context).inflate(R.layout.window_bobble, null);
        triangleView = view.findViewById(R.id.triangleView);
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        measuredWidth = view.getMeasuredWidth();
        measuredHeight = view.getMeasuredHeight();
        Log.d(TAG, "initPopupWindowView: width:" + measuredWidth + "   height:" + measuredHeight);
    }

    public void setAttachView(View view) {
        location = new int[2];
        view.getLocationOnScreen(location);
        attachView = view;
    }

    public void show() {
        mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.showAtLocation(attachView, Gravity.TOP, 20, location[1] - measuredHeight);
        view.getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    private void calculatePositionInWindow() {
        int[] viewLocation = new int[2];
        view.getLocationOnScreen(viewLocation);
        int attachViewCentre = location[0] + attachView.getWidth() / 2;
        int marginLeft = attachViewCentre - viewLocation[0] - triangleView.getWidth() / 2;
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) triangleView.getLayoutParams();
        params.setMargins(marginLeft, 0, 0, 0);
        triangleView.setLayoutParams(params);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onGlobalLayout() {
        view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        calculatePositionInWindow();
    }
}
